package controller

import (
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/utils/def"
)

func GetOpen(context def.Context, app *models.App, openId string) (*models.UserOpen, error) {
	var userOpen models.UserOpen
	var err error
	var ok bool
	err = wrap.Cache("open/"+openId, &userOpen, func() error {
		if ok, err = models.UserOpenModel.PK(openId).
			Where("=", "app_id", app.Id).One(&userOpen); !ok {
			return EmptyExceptionDetail("用户不存在", err)
		}
		return nil
	})

	return &userOpen, err
}

func GetOpenList(context def.Context, app *models.App, openIds []string) ([]models.UserOpen, error) {
	var userList []models.UserOpen
	query := models.UserOpenModel.Query()
	query.Where("=", "app_id", app.Id).Where("in", "id", openIds)
	_, err := query.Find(&userList)
	if err != nil {
		return nil, SystemExceptionDetail("获取用户失败", err)
	}
	return userList, nil
}

func ChangeOpen(context def.Context, app *models.App, openId string, nickName string, avatar string) error {
	data := map[string]interface{}{}
	if nickName != "" {
		data["nick_name"] = nickName
	}
	if avatar != "" {
		data["avatar"] = avatar
	}

	return UpdateOpen(context, app, openId, data)
}

func SearchUserList(context def.Context, app *models.App, keyword string, page int, number int) ([]models.UserOpen, error) {
	var userList []models.UserOpen
	query := models.UserOpenModel.Query()
	if keyword != "" {
		query.WhereSql("`nick_name` like ?", "%"+keyword+"%")
	}
	query.Where("=", "app_id", app.Id)
	_, err := query.FindAndCount(&userList, page, number)
	if err != nil {
		return nil, SystemExceptionDetail("搜索用户失败", err)
	}
	return userList, nil
}

func UpdateOpenPreferences(context def.Context, app *models.App, openId string, preferences map[string]string) error {
	data := map[string]interface{}{}
	data["preferences"] = preferences
	return UpdateOpen(context, app, openId, data)
}

func GetOpenStore(context def.Context, app *models.App, openId string, key string) (interface{}, error) {
	userOpen, err := GetOpen(context, app, openId)
	if err != nil {
		return nil, err
	}
	if userOpen.Store == nil {
		return nil, nil
	}
	if v, ok := userOpen.Store[key]; ok {
		return v, nil
	} else {
		return nil, nil
	}
}

func UpdateOpenStore(context def.Context, app *models.App, openId string, key string, value interface{}) error {
	userOpen, err := GetOpen(context, app, openId)
	if err != nil {
		return err
	}
	if userOpen.Store == nil {
		userOpen.Store = make(map[string]interface{})
	}
	userOpen.Store[key] = value
	return UpdateOpen(context, app, openId, map[string]interface{}{
		"store": userOpen.Store,
	})
}

func UpdateOpen(context def.Context, app *models.App, openId string, data map[string]interface{}) error {
	return wrap.SingleClean("open/"+openId, func() error {
		if _, err := models.UserOpenModel.PK(openId).
			Where("=", "app_id", app.Id).Update(data); err != nil {
			return SystemExceptionDetail("更新用户失败", err)
		}
		return nil
	}, false)
}
